#!/user/bin/env python
# -*- coding: UTF-8 -*-
# Author: xieyuheng
# Date: 2024/2/26
"""
该文件用于 所有页面的公共方法的集合
"""
import os
import time
import uiautomation as auto
import pyautogui
import constant
from page.browser import Browser
from utils.utils_operation import get_current_time, cal_ratio
from utils.utils_log import loggerCase
from common.soft_operate import close_app_kill
from common_ai_img import AIButton, Icon

file = constant.ui_log_image_path + os.sep + get_current_time(format="%Y_%m_%d_%H_%M_%S")
os.mkdir(file)

class BasePage:
    """基本页面类"""
    pyautogui.PAUSE = 0.2

    def __init__(self):
        Browser()
        # 进度条
        self.__waiting = AIButton(Icon("waiting"))

    def loading(self, wait_time=1):
        """
        加载进度条
        :param wait_time:
        :return:
        """
        loggerCase.debug("加载进度条")
        while self.judge_element_exist(element=self.__waiting, max_wait_time=1,
                                       is_need_screen=False, is_end=False, max_retries=1):
            time.sleep(wait_time)
        loggerCase.debug("加载完成")

    def wait_time(self, wait_time):
        """
        进行等待
        :param wait_time: 等待时间
        :return:
        """
        loggerCase.debug("开始等待")
        _wait_time = int(wait_time)
        time.sleep(_wait_time)
        loggerCase.debug("开始结束")

    def close(self):
        """
        关闭软件
        :return:
        """
        close_app_kill()


    def add_screen(self, text=time.strftime("%Y%m%d%H%M%S")):
        """
        截图
        :param text: 截图的名字
        :return:
        """
        # 截图放在项目中
        picture_path = constant.picture_path + "\\" + text + ".png"
        pyautogui.screenshot().save(picture_path)
        loggerCase.debug(f"截图到 -> {picture_path}")

    def add_screen_platform(self):
        """
        截图放在static中
        :param text:
        :return:
        """
        text = str(
            time.strftime(f"%Y_%m_%d_%H_%M_%S", time.localtime(
                time.time())))
        file_path = file + os.sep + text + '.png'
        pyautogui.screenshot().save(file_path)
        return os.path.relpath(file_path, constant.test_report_ui_path)

    # ===========================AI操作==================================================================
    def judge_element_exist(self, element, max_wait_time=1, is_need_screen=True, is_end=True, max_retries=3):
        """
        element:元素
        max_wait_time：最大等待时间
        is_need_screen： 是否需要截图
        """
        count = 0
        while count < max_retries:
            if element.exists(timeout=max_wait_time):
                return True
            else:
                count += 1
                time.sleep(0.5)
        if is_need_screen:
            self.add_screen()
        if is_end:
            loggerCase.error("元素不存在", extra={"image_path": self.add_screen_platform()})
            raise Exception("元素不存在异常")
            # sys.exit()
        else:
            return False

    def click(self, element, times=1, max_wait_time=1, is_need_judge=True):
        """
        最大等待时间：遇到有进度条时，需要用到
        element:元素
        times：点击次数
        max_wait_time：最大等待时间
        is_need_screen： 是否需要截图
        """
        if is_need_judge:
            if self.judge_element_exist(element, max_wait_time=max_wait_time):
                for i in range(times):
                    element.click()
        else:
            for i in range(times):
                element.click()

    def send_key(self, element, text):
        """
        输入内容
        :param element: 元素
        :param text: 需要输入的文本
        :return:
        """
        if self.judge_element_exist(element):
            element.click()
            auto.SendKeys("{Ctrl}a")
            pyautogui.typewrite(text)
            time.sleep(0.5)
            self.ENTER()

    def input_keys(self, text):
        """
        键盘输入
        """
        loggerCase.info("键盘输入")
        pyautogui.typewrite(text)

    def press_key(self, text, wait_time=1.0):
        """
        按下按钮
        """
        loggerCase.info("使用auto按下键盘")
        auto.PressKey(text, waitTime=wait_time)

    def ENTER(self):
        """回车"""
        pyautogui.press("enter")
        self.loading()

    # 进入各个模式
    # 参数：分辨率，如1920,1080,默认就是1920*1080，标定--calib，扫描模式--scan_mode，扫描--scan，后处理--post_processing,测量--measurement
    # 分辨率是1920*1080，导航栏两端宽400，高度是110
    # @common.run_time
    def enter_mode(self, mode_name="scan_mode"):
        """
        导航条跳转
        """
        ratio = cal_ratio()
        # 减去头尾的400，中间是平均分的(1920 - 800) / 5 = 224，每个圆点分别为400，624，848，1072，1296，1520
        if mode_name == "Device":
            auto.Click(round(422 * ratio), round(105 * ratio), waitTime=1)
            loggerCase.info("点击重连")
        if mode_name == "scan_mode":
            auto.Click(round(689 * ratio), round(105 * ratio), waitTime=1)
            loggerCase.info("进入扫描模式")
        if mode_name == "scan":
            auto.Click(round(960 * ratio), round(105 * ratio), waitTime=1)
            loggerCase.info("进入扫描界面")
        if mode_name == "post_processing":
            auto.Click(round(1230 * ratio), round(105 * ratio), waitTime=1)
            loggerCase.info("进入后处理")
        if mode_name == "measurement":
            auto.Click(round(1480 * ratio), round(105 * ratio), waitTime=1)
            loggerCase.info("进入测量")

if __name__ == '__main__':
    time.sleep(3)
    BasePage().input_keys("111")
